package lab.springai.alibaba.controller;


import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*") // 支持所有来源的跨域请求
public class ChatController {

    private final ChatClient chatClient;

    @Value("classpath:your-prompt-template.st")
    Resource promptTemplateResource;

    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/steamChat")
    public Flux<String> steamChat(@RequestParam String input){
        // 读取模板文件时显式指定字符编码
//        String templateContent = new String(Files.readAllBytes(Paths.get(promptTemplateResource.getFile().toURI())), "UTF-8");
        PromptTemplate promptTemplate = new PromptTemplate(promptTemplateResource);
        Prompt prompt = promptTemplate.create(Map.of("input", input));
        return chatClient.prompt(prompt).stream().content().map(data -> new String(data.getBytes(), StandardCharsets.UTF_8));
    }


}
